import { getUserInfo, Login } from '@/api/user'
import { setToken, getToken, removeToken } from '@/utils/auth'
const state = {
  token: getToken(),
  userInfo: {}
}
const mutations = {
  setToken(state, token) {
    state.token = token
    // 将token保存到cookie缓存中
    setToken(token)
  },
  removeToken(state) {
    state.token = null
    removeToken()
  },
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  }
}
const actions = {
  async login(context, data) {
    // 发送请求
    const res = await Login(data)
    // 获取token
    // 提交mutations
    context.commit('setToken', res)
  },
  async getUserInfo(context) {
    const res = await getUserInfo()
    // 发送请求获取用户信息
    context.commit('setUserInfo', res)
  },
  logout(context) {
    // 清除token
    context.commit('removeToken')
    // 清除用户信息
    context.commit('setUserInfo', {})
  }
}
const getters = {}
export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
